// import { parse, Font } from 'opentype.js';

// @ts-ignore
import { create } from 'fontkit';
import loadScript from './load-script';

// var fontkit = require('fontkit');

/**
 * @description 加载内置字体
 */
class FontMap {
  loading: boolean = false;

  baseLocation: URL | null = null;

  fontFile: {
    [k: string | number]: {
      getPath: (
        s: string,
        n?: number,
        c?: number,
        v?: number,
        op?: { hinting?: boolean; kerning?: boolean; features?: boolean },
      ) => { glyphs: any; toSVG: (a: number) => string; Path: any };
    };
  } = {};

  intervalTimer: any | null = null;
  callbacks: {
    funs: (l: boolean) => void;
    k: string | number;
    file: ArrayBuffer;
  }[] = [];

  constructor() {
    this.getBaseUrl();
    this.init();
  }

  init() {
    if (!window.opentype) {
      this.loading = true;
      // const baseUrl = this.getBaseUrl();

      if (this.baseLocation) {
        loadScript(this.baseLocation.href + 'opentype.min.js')
          .then(() => {
            this.loading = false;
          })
          .catch(() => {
            // 加载js失败，尝试加载外网
            // cdn方式引入opentype.js
            loadScript('https://felibs.nuonuo.com/libs/opentype.min.js')
              .then(() => {
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
                // 加载js失败，尝试加载本地js
                console.warn('加载字体渲染文件失败，请手动引入opentype.js');
                //
              });
            //
          });
      } else {
        loadScript('https://felibs.nuonuo.com/libs/opentype.min.js')
          .then(() => {
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
            // 加载js失败，尝试加载本地js
            console.warn('加载字体渲染文件失败，请手动引入opentype.js');
            //
          });
      }
    } else {
      // callback && callback();
    }
  }

  getBaseUrl() {
    if (typeof document !== 'undefined' && document.currentScript) {
      // @ts-ignore
      this.baseLocation = new URL('./', document.currentScript.src || '');
    } else {
      this.baseLocation = null;
      console.warn('获取地址失败！');
    }
  }

  setFontFile(key: string | number, file: ArrayBuffer, callback: (r: boolean) => void) {
    try {
      this.fontFile[key] = create(file);
      callback?.(false);
    } catch (err) {
      callback?.(false);
    }

    // if (!window.opentype) {
    //   if (this.loading) {
    //     // 等待 opentype.min.js 加载完成
    //     if (!this.intervalTimer) {
    //       this.intervalTimer = setInterval(() => {
    //         if (!this.loading) {
    //           if (this.intervalTimer) {
    //             clearInterval(this.intervalTimer);
    //           }
    //           if (this.callbacks.length) {
    //             this.callbacks.forEach(({ k, funs, file: f }) => {
    //               try {
    //                 if (!this.fontFile[k]) {
    //                   this.fontFile[k] = window.opentype.parse(f);
    //                 }
    //                 funs(true);
    //               } catch (er) {
    //                 console.warn(er);
    //                 funs(false);
    //               }
    //             });
    //           }
    //         }
    //       }, 30);
    //     }
    //     this.callbacks.push({ k: key, file, funs: callback });
    //   } else {
    //     this.init();
    //   }
    //   return;
    // }
    // try {
    //   if (window.opentype && !this.fontFile[key]) {
    //     this.fontFile[key] = window.opentype.parse(file);
    //   }
    //   callback(true);
    // } catch (err) {
    //   console.warn(err);
    //   callback(false);
    // }
  }

  getFontFile(key: string | number, txt: string, x: number, y: number, s: number): string[] {
    // @ts-ignore
    const run = this.fontFile[key].layout(txt);
    // @ts-ignore
    // const glyph = this.fontFile[key].getGlyph(txt); // 获取字符 'A' 的字形数据
    console.log('run.glyphs:', run.glyphs);
    let result: string[] = [];
    if (run.glyphs?.length) {
      // @ts-ignore
      run.glyphs.forEach((t, inx) => {
        // const path = t.path.toSVG(2);
        result.push(t.path.toSVG(4));
      });
    }
    return result;
    // return this.fontFile[key].getPath(txt, x, y, s, { hinting: true }).toSVG(2);
  }

  destroy() {
    this.fontFile = {};
    this.callbacks = [];
    if (this.intervalTimer) {
      clearInterval(this.intervalTimer);
    }
  }
}

export default new FontMap();
